/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback, useRef, useEffect } from 'react';
import { connect } from 'dva';
import { useInterval, useUpdateEffect } from 'ahooks';
import { Chart, Geom, Axis, Tooltip, Legend } from 'bizcharts';
import DataSet from '@antv/data-set';
import moment from 'moment';
import CommonBorder from './Wrappers/CommonBorder';
import NoDate from './Wrappers/NoDate';
import { axisLabel, gradualTextColumn } from './_utils';
import styles from '../commonChart.less';

const legends = {
  count: '扫描数',
};

const ds = new DataSet();

const InOutNumbers = ({
  branchId,
  dispatch,
  isParentFull,
  loading,
  screenToken,
  currentLevel,
  type,
}) => {
  const heightRef = useRef({});
  const [height, setHeight] = useState(0);
  const [list, setList] = useState([]);
  const [hasData, setHasData] = useState(false);
  const timer = useRef(null);

  const fetchData = useCallback(
    () => {
      dispatch({
        type: 'chartData/pdaSummary',
        payload: {
          day: 7,
          brand: 'all',
          cm_id: 'all',
          code: branchId,
          token: screenToken,
          level: currentLevel,
          type,
        },
      }).then((res = []) => {
        const val = ds
          .createView()
          .source(res)
          .transform({
            type: 'fold',
            fields: ['count'],
            key: 'city',
            value: 'number',
          });
        setHasData(res.length > 0);
        setList(val);
      });
    },
    [branchId, dispatch, screenToken, currentLevel, height], // 监听高度，自动更新接口
  );

  useEffect(
    () => {
      timer.current = setTimeout(() => {
        heightRef.current && setHeight(heightRef.current.clientHeight);
      }, 1000);
      return () => {
        timer.current && clearTimeout(timer.current);
      };
    },
    [isParentFull, heightRef],
  );

  useUpdateEffect(fetchData, [fetchData]);

  useInterval(fetchData, 60 * 60 * 1000);

  const handleTooltipChange = ev => {
    ev.items.forEach(data => {
      data.name = legends ? legends[data.name] : data.name;
    });
  };

  return (
    <CommonBorder title="近7日共配扫描数" loading={loading}>
      <div style={{ height: '100%' }} ref={heightRef}>
        {hasData ? (
          <Chart
            className={styles.chart}
            style={{ backgroundColor: 'rgba(15, 24, 55, 0.7)' }}
            plotBackground={{
              fill: '#7d95f3',
              fillOpacity: 0.05,
              stroke: '#7d95f3',
              strokeOpacity: 0.1,
              lineWidth: 1,
              radius: 2,
            }}
            onTooltipChange={handleTooltipChange}
            color="name"
            height={height}
            data={list}
            forceFit
            padding={[50, 'auto', 'auto', 'auto']}
          >
            <Legend
              name="city"
              itemFormatter={text => (legends ? legends[text] : text)}
              textStyle={{
                fill: gradualTextColumn, // 文本的颜色
                fontSize: 18,
              }}
              marker="circle"
              position="top-right"
            />
            <Axis
              name="days"
              label={{ ...axisLabel, formatter: val => moment(val).format('MM-DD') }}
              tickLine={null}
            />
            <Axis
              grid={null}
              name="number"
              label={{
                ...axisLabel,
                formatter: val => (val > 10000 ? `${val / 10000}万` : val),
              }}
            />
            <Tooltip
              crosshairs={{
                type: 'y',
              }}
            />
            <Geom
              type="line"
              position="days*number"
              color={['city', '#5b9dfd-#e93ca7']}
              size={2}
              shape="smooth"
            />
          </Chart>
        ) : (
          <NoDate title="暂无数据" style={{ height }} />
        )}
      </div>
    </CommonBorder>
  );
};

export default connect(({ chartData, loading, global }) => ({
  branchId: chartData.currentAreaInfo.branchId,
  screenToken: global.screenToken,
  currentLevel: chartData.currentAreaInfo.currentLevel,
  loading: loading.effects['chartData/pdaSummary'],
}))(React.memo(InOutNumbers));
